//创建用户相关的小仓库
import { defineStore } from 'pinia'
//引入接口
import { reqLogin, reqUserInfo, reqLogout,reqRegister } from '@/api/user'
import type { UserState } from './types/type'
//引入操作本地存储的工具方法
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
//引入路由（常量路由）
import { constantRoute } from '@/router/routes'
import { ElMessage } from 'element-plus'

//创建用户小仓库
const useUserStore = defineStore('User', {
  //小仓库存储数据地方
  state: (): UserState => {
    return {
      token: GET_TOKEN(), //用户唯一标识token
      menuRoutes: constantRoute, //仓库存储生成菜单需要数组（路由）
      username: '',
      avatar: '',
      nickName: '',
      phonenumber: '',
      email: '',
      sex: '',
      createTime: '',
      delFlag: '',
      password: '',
      roles: null,
      status: '',
      updateTime: null,
      userId: 0,
    }
  },
  //处理异步|逻辑地方
  actions: {
     //用户注册的方法
     async userRegister(data: any) {
      //注册请求
      const result: any = await reqRegister(data)
      if (result.code == 0) {
        ElMessage(result.data)
        //保证当前async函数返回一个成功的promise函数
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },

    //用户登录的方法
    async userLogin(data: any) {
      //登录请求
      const result: any = await reqLogin(data)
      if (result.code == 0) {
        //pinia仓库存储token
        //由于pinia|vuex存储数据其实利用js对象
        this.token = result.data.token as string
        //本地存储持久化存储一份
        SET_TOKEN(result.data.token as string)
        //保证当前async函数返回一个成功的promise函数
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
    //获取用户信息方法
    async userInfo() {
      //获取用户信息进行存储
      const result = await reqUserInfo()
      console.log(result)

      if (result.code == 0) {
        this.username = result.data.userName
        this.avatar = result.data.avatar
        this.nickName = result.data.nickName
        this.phonenumber = result.data.phonenumber
        this.email = result.data.email
        this.sex = result.data.sex
        this.createTime = result.data.createTime
        this.delFlag = result.data.delFlag
        this.password = result.data.password
        this.roles = result.data.roles
        this.status = result.data.status
        this.updateTime = result.data.updateTime
        this.userId = result.data.userId
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
    //退出登录
    async userLogout() {
      const result = await reqLogout()
      if (result.code == 0) {
        //本地数据清空
        this.token = ''
        this.username = ''
        this.avatar = ''
        REMOVE_TOKEN()
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
  },
  getters: {},
})
//对外暴露小仓库
export default useUserStore
